package org.lzy.shop.fragment

import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textfield.TextInputEditText
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnBindView
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.activity.SearchActivity
import org.lzy.shop.activity.SearchResultActivity
import org.lzy.shop.adapter.CouponHomeAdapter
import org.lzy.shop.adapter.HomeCategorAllAdapter
import org.lzy.shop.adapter.HomeCategoryAdapter
import org.lzy.shop.adapter.HomeGoodsAdapter
import org.lzy.shop.adapter.HomeRecommendAdapter
import org.lzy.shop.base.BaseMvvmFragment
import org.lzy.shop.databinding.FragHomeBinding
import org.lzy.shop.good.GoodInfoActivity
import org.lzy.shop.response.HomeResponse
import org.lzy.shop.util.BannerManager
import org.lzy.shop.util.setUrlRound
import org.lzy.shop.viewmodel.HomeViewModel
import kotlin.math.abs

/**
 * 主页fragment
 */
class HomeFragment: BaseMvvmFragment<FragHomeBinding, HomeViewModel>(FragHomeBinding::inflate) {

    private val homeCategoryAdapter: HomeCategoryAdapter by lazy { HomeCategoryAdapter() }
    private val homeGoodsAdapter: HomeGoodsAdapter by lazy { HomeGoodsAdapter() }
    private val homeRecommendAdapter: HomeRecommendAdapter by lazy { HomeRecommendAdapter() }
    private val homeCategoryAllAdapter: HomeCategorAllAdapter by lazy { HomeCategorAllAdapter() }
    private var couponList: MutableList<HomeResponse.CouponDTO>? = ArrayList()

    // 定义触摸位置跟踪变量
    private var lastX = 0f
    private var lastY = 0f

    private var bannerData: List<HomeResponse.BannerDTO>? = null
    private val bannerManager: BannerManager<HomeResponse.BannerDTO> by lazy {
        BannerManager(
            viewPager2 = binding.bannerViewpager,
            indicatorsContainer = binding.bannerIndicator,
            lifecycleOwner = viewLifecycleOwner,
            dataList = bannerData ?: emptyList(),
            autoScrollDelay = 3000,
            isInfiniteLoop = true
        ).apply {
            // 设置图片加载器
            setImageLoader {
                    imageView, item ->
                setUrlRound(item.pic,8f,imageView)
            }
        }
    }

    override fun initView() {
        // 设置RecyclerView布局管理器和适配器
        setupRecyclerViews()
        // 设置刷新监听器
        setupRefreshListener()
        // 设置各个点击事件
        setupCategoryClickListener()
        setupGoodsClickListener()
        setupRecommendClickListener()
        setupCategoryAllClickListener()
    }

    override fun requestData() {
        lifecycleScope.launch {
            // 先加载关键数据
            mViewModel.getHomeGoods()
            mViewModel.getHomeGoodAll()
        }
    }

    override fun initData() {
        // 观察主页数据
        observeHomeData()
        // 观察网络错误
        observeHomeError()
        // 观察全部商品数据
        observeHomeGoodData()
        // 观察优惠券领取结果
        observeCouponReceiveResult()

    }

    override fun allClick() {
        // 恢复顶部搜索栏点击跳转功能
        binding.searchMainLl.setOnClickListener {
            startActivity(SearchActivity::class.java)
        }
        binding.searchMainLl.apply {
            // 设置搜索框不可编辑，点击整体区域跳转
            binding.searchMainLl.findViewById<TextInputEditText>(R.id.textInputEditText)?.apply {
                isFocusable = false
                isFocusableInTouchMode = false
                hint = ""
                // 确保点击输入框本身也能跳转
                setOnClickListener {
                    startActivity(SearchActivity::class.java)
                }
            }
            // 确保TextInputLayout点击本身也能跳转
            setOnClickListener {
                startActivity(SearchActivity::class.java)
            }
        }

        // 查看全部
        binding.hotMore.setOnClickListener {
            startActivity(SearchResultActivity::class.java)
        }
        // 无网络后正常后按重新加载
        binding.netErrorInclude.ivReloading.setOnClickListener {
            mViewModel.getHomeGoods()
            mViewModel.getHomeGoodAll()
        }
        // 领取
        setupCouponReceiveClickListener()
    }

    /**
     * 设置RecyclerViews的布局管理器和适配器
     */
    private fun setupRecyclerViews() {
        // 分类RecyclerView
        binding.frgHomeGirdview.apply {
            layoutManager = GridLayoutManager(activity, 5)
            adapter = homeCategoryAdapter
        }

        // 限时抢购RecyclerView
        binding.frgHomeLvTimelimitt.apply {
            layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.HORIZONTAL, false)
            adapter = homeGoodsAdapter
            // 禁用嵌套滑动，提升滑动流畅性
            isNestedScrollingEnabled = false
            setHasFixedSize(true)
            //解决限制列表水平滑动冲突
            addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
                private var startX = 0f
                private var startY = 0f
                override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                    when (e.action) {
                        MotionEvent.ACTION_DOWN -> {
                            startX = e.x
                            startY = e.y
                            // 当按下时，请求父控件不要拦截触摸事件
                            rv.parent.requestDisallowInterceptTouchEvent(true)
                        }
                        MotionEvent.ACTION_MOVE -> {
                            // 获取滑动方向和距离
                            val dx = abs(e.x - startX)
                            val dy = abs(e.y - startY)
                            // 优化判定条件，只有当水平滑动明显强于垂直滑动时才不允许拦截
                            rv.parent.requestDisallowInterceptTouchEvent(dx > dy * 1.5f)
                        }
                        MotionEvent.ACTION_UP,
                        MotionEvent.ACTION_CANCEL -> {
                            // 当抬起或取消时，允许父控件拦截
                            rv.parent.requestDisallowInterceptTouchEvent(false)
                        }
                    }
                    return false
                }

                override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {}

                override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
            })
        }

        // 热门推荐RecyclerView
        binding.frgHomeLvRecommandGoods.apply {
            layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
            adapter = homeRecommendAdapter
            isNestedScrollingEnabled = false // 禁用嵌套滑动
            setHasFixedSize(true) // 固定大小提升性能
        }

        // 全部商品RecyclerView
        binding.frgHomeCategoryall.apply {
            layoutManager = GridLayoutManager(activity, 2)
            adapter = homeCategoryAllAdapter
            isNestedScrollingEnabled = false // 禁用嵌套滑动
            setHasFixedSize(true) // 固定大小提升性能

        }
    }

    /**
     * 设置刷新监听器
     */
    private fun setupRefreshListener() {
        // 设置下拉刷新
        binding.refreshLayout.apply {
            setOnRefreshListener {
                mViewModel.getHomeGoods()
                mViewModel.getHomeGoodAll()
            }
            // 设置刷新颜色
            setColorSchemeResources(R.color.colorPrimary)
        }
    }

    /**
     * 设置分类点击事件
     */
    private fun setupCategoryClickListener() {
        homeCategoryAdapter.setOnItemClickListener { adapter, _, position ->
            val response = adapter.getItem(position)
            response?.let {
                val list = ArrayList<Int?>()
                when (response.name) {
                    "手机" -> { list.add(11); list.add(12); list.add(13) }
                    "服装" -> { list.add(20); list.add(21); list.add(22) }
                    "电脑" -> { list.add(14); list.add(15); list.add(16); list.add(17); list.add(18); list.add(19) }
                    "优惠" -> { list.add(41); list.add(42); list.add(43) }
                    "家电" -> { list.add(32); list.add(33); list.add(34); list.add(35); list.add(36) }
                    "户外" -> { list.add(39); list.add(40) }
                    "潮鞋" -> { list.add(37) }
                    "会员" -> { list.add(26); list.add(27) }
                    "包包" -> { list.add(23); list.add(24); list.add(25) }
                    "网络" -> { list.add(28); list.add(29); list.add(30); list.add(31) }
                }
                val bundle = Bundle()
                bundle.putIntegerArrayList(Constant.TYPE_ID, list)
                startActivity(SearchResultActivity::class.java, bundle)
            }
        }
    }

    /**
     * 设置限时抢购商品点击事件
     */
    private fun setupGoodsClickListener() {
        homeGoodsAdapter.setOnItemClickListener { adapter, _, position ->
            val response = adapter.getItem(position)
            response?.let {
                navigateToGoodInfo(response.id, response.mainPic)
            }
        }
    }

    /**
     * 设置热门推荐商品点击事件
     */
    private fun setupRecommendClickListener() {
        homeRecommendAdapter.setOnItemClickListener { adapter, _, position ->
            val response = adapter.getItem(position)
            response?.let {
                navigateToGoodInfo(response.id, response.mainPic)
            }
        }
    }

    /**
     * 设置全部商品点击事件
     */
    private fun setupCategoryAllClickListener() {
        homeCategoryAllAdapter.setOnItemClickListener { adapter, _, position ->
            val response = adapter.getItem(position)
            response?.let {
                navigateToGoodInfo(response.id, response.mainPic)
            }
        }
    }

    /**
     * 设置优惠券领取点击事件
     */
    private fun setupCouponReceiveClickListener() {
        binding.couponReceive.setOnClickListener {
            BottomDialog.show(object : OnBindView<BottomDialog?>(R.layout.dialog_bottom_coupon) {
                override fun onBind(dialog: BottomDialog?, view: View) {
                    val couponRv = view.findViewById<RecyclerView>(R.id.coupon_rv)
                    val couponHomeAdapter = CouponHomeAdapter()
                    couponRv.apply {
                        layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
                        adapter = couponHomeAdapter
                    }
                    couponList?.let { list ->
                        if (list.isNotEmpty()) {
                            couponHomeAdapter.submitList(list)
                        }
                    }
                    couponHomeAdapter.addOnItemChildClickListener(R.id.get_now) {
                            adapter, _, position ->
                        val item = adapter.getItem(position) as? HomeResponse.CouponDTO
                        item?.let {
                            mViewModel.couponReceive(item.id)
                        }
                    }
                }
            }).setAllowInterceptTouch(false).setMaskColor("#4D000000".toColorInt())
        }
    }

    /**
     * 观察主页数据
     */
    private fun observeHomeData() {
        mViewModel.homeLiveData.observeWithLifecycle(viewLifecycleOwner) { homeResponse ->
            finishRefresh()
            homeResponse?.let {
                // 设置Banner，修复图片圆角对齐问题
                setupBanner(it.banner)

                // 设置分类数据
                it.category?.let {
                    homeCategoryAdapter.submitList(it)
                }

                // 设置限时抢购数据
                it.flashSale?.let {
                    homeGoodsAdapter.submitList(it)
                }

                // 设置热门推荐数据
                it.recommend?.let {
                    homeRecommendAdapter.submitList(it)
                }

                // 显示内容，隐藏错误页面
                binding.netErrorInclude.netErrorLayout.visibility = View.GONE
                binding.nestedsv.visibility = View.VISIBLE

                // 设置优惠券信息
                it.coupon?.let {
                    if (it.isNotEmpty()) {
                        couponList = it
                        val info: MutableList<String?> = ArrayList()
                        for (i in 0 until it.size) {
                            info.add(it[i].title)
                        }
                        binding.marqueeView.startWithList(info)
                    }
                }
            }
        }
    }

    /**
     * 设置Banner，修复图片圆角对齐问题
     */
    private fun setupBanner(bannerList: List<HomeResponse.BannerDTO>?) {
        bannerList?.let {
            if (bannerList.isNotEmpty()) {
                // 保存banner数据
                bannerData = bannerList
                // 设置数据到bannerManager
                bannerManager.setData(bannerList)
                // 初始化并开始轮播
                bannerManager.initialize()
            }
        }
    }

    /**
     * 观察网络错误
     */
    private fun observeHomeError() {
        mViewModel.homeErrorData.observeWithLifecycle(viewLifecycleOwner) {
                errorCode ->
            if (errorCode == 1007) {
                binding.netErrorInclude.netErrorLayout.visibility = View.VISIBLE
                binding.nestedsv.visibility = View.GONE
            }
        }
    }

    /**
     * 观察全部商品数据
     */
    private fun observeHomeGoodData() {
        mViewModel.homeGoodLiveData.observeWithLifecycle(viewLifecycleOwner) { homeGoodAllResponse ->
            finishRefresh()
            homeGoodAllResponse?.let {
                it.list?.let {
                    if (it.isNotEmpty()) {
                        homeCategoryAllAdapter.submitList(it)
                    }
                }
            }
        }
    }

    /**
     * 观察优惠券领取结果
     */
    private fun observeCouponReceiveResult() {
        // 保存job引用以便在Fragment销毁时取消
        var couponReceiveJob: Job? = null
        mViewModel.couponReceiveData.observeWithLifecycle(viewLifecycleOwner) { string ->
            dismissLoadingDialog()
            // 取消之前的job
            couponReceiveJob?.cancel()
            couponReceiveJob = lifecycleScope.launch {
                delay(2000)
                if (isActive) { // 检查协程是否仍处于活跃状态
                    showToast(string)
                }
            }
        }

        mViewModel.couponReceiveFailedData.observeWithLifecycle(viewLifecycleOwner) {
                string ->
            dismissLoadingDialog()
            // 取消之前的job
            couponReceiveJob?.cancel()
            couponReceiveJob = lifecycleScope.launch {
                delay(2000)
                if (isActive) { // 检查协程是否仍处于活跃状态
                    TipDialog.show(string, WaitDialog.TYPE.ERROR)
                }
            }
        }
    }

    /**
     * 跳转到商品详情页
     */
    private fun navigateToGoodInfo(goodId: Int, goodPic: String?) {
        val bundle = Bundle()
        bundle.putInt(Constant.GOODID, goodId)
        bundle.putString(Constant.GOODPIC, goodPic)
        startActivity(GoodInfoActivity::class.java, bundle)
    }

    private fun finishRefresh() {
        // 停止刷新
        binding.refreshLayout.isRefreshing = false

    }

    override fun onDestroyView() {
        super.onDestroyView()
        bannerManager.onDestroy(viewLifecycleOwner)
        // 清空数据引用，避免内存泄漏
        bannerData = null
        couponList?.clear()
        // 移除所有适配器引用
        binding.frgHomeGirdview.adapter = null
        binding.frgHomeLvTimelimitt.adapter = null
        binding.frgHomeLvRecommandGoods.adapter = null
        binding.frgHomeCategoryall.adapter = null
        // 停止刷新并移除监听器
        binding.refreshLayout.isRefreshing = false
        binding.refreshLayout.setOnRefreshListener(null)

    }

}